package com.mvc.demo.controller;

import com.lowagie.text.Font;
import com.lowagie.text.*;
import com.lowagie.text.pdf.PdfPCell;
import com.lowagie.text.pdf.PdfPTable;
import com.mvc.demo.bean.User;
import com.mvc.demo.service.PdfExportService;
import com.mvc.demo.service.PdfView;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.View;

import java.awt.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @author H
 * @date 2023/1/8
 */
@Controller
@RequestMapping("pdf")
public class TestExportPdfController {

    @GetMapping("export")
    public ModelAndView exportPdf() {
        // 用户列表
        List<User> users = new ArrayList<>();
        User user = new User();
        user.setUsername("小明");
        user.setAge(10);
        users.add(user);
        // 定义pdf视图
        View view = new PdfView(exportService());
        ModelAndView modelAndView = new ModelAndView();
        // 设置视图
        modelAndView.setView(view);
        // 加入数据模型
        modelAndView.addObject("userList", users);
        return modelAndView;
    }

    /**
     * 到处pdf自定义
     * @return
     */
    private PdfExportService exportService() {
        // 使用lambda表达式定义自定义导出
        return (model, document, writer, request, response) -> {
            try {
                // A4纸张
                document.setPageSize(PageSize.A4);
                // 标题
                document.addTitle("用户信息");
                // 换行
                document.add(new Chunk("\n"));
                // 表格，2列
                PdfPTable table = new PdfPTable(2);
                // 单元格
                PdfPCell cell;
                // 字体，定义为蓝色加粗
                Font font = new Font();
                font.setColor(Color.BLUE);
                font.setStyle(Font.BOLD);

                cell = new PdfPCell(new Paragraph("user_name", font));
                // 居中对齐
                cell.setHorizontalAlignment(1);
                table.addCell(cell);
                cell = new PdfPCell(new Paragraph("age", font));
                cell.setHorizontalAlignment(1);
                table.addCell(cell);
                // 获取数据模型中的用户列表
                List<User> userList = (List<User>) model.get("userList");
                for (User user : userList) {
                    document.add(new Chunk("\n"));
                    cell = new PdfPCell(new Paragraph(user.getUsername()));
                    table.addCell(cell);
                    cell = new PdfPCell(new Paragraph(user.getAge()));
                    table.addCell(cell);
                }
                // 在文档中加入表格
                document.add(table);
            } catch (DocumentException e) {
                throw new RuntimeException(e);
            }
        };

    }
}
